<template>
  <a-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    @ok="handleSubmit"
    @cancel="close"
    :cancelText="$t('systemManagement.close')"
    style="top:5%;height: 100%;overflow-y: hidden"
    id="select-material-modal"
    wrapClassName="ant-modal-cust-warp"
  >
    <a-row :gutter="10" class="mater-a40596bz" >
      <a-col :md="4" :sm="24" >
              <template>
                <div style="background: #fff;padding-left:16px; margin-top: 5px;height: 558px;border: 1px solid #619ddb;overflow-x:hidden;overflow-y:scroll">
                <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                <span style="user-select: none">
                  <a-tree
                    multiple
                    @select="onSelect"
                    @rightClick="rightHandle"
                    :selectedKeys="selectedKeys"
                    :checkedKeys="checkedKeys"
                    :treeData="categoryTree"
                    :checkStrictly="checkStrictly"
                    :expandedKeys="iExpandedKeys"
                    :autoExpandParent="true"
                    @expand="onExpand"/>
                  </span>
                </a-dropdown>
                </div>
              </template>
      </a-col>
      <a-col :md="20" :sm="24">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="onSearch">
            <a-row :gutter="24">
              <a-col :md="6" :sm="8">
                <a-form-item :label="$t('setailManagement.commodity')" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <a-input ref="material" :placeholder="$t('reportQuery.barcodeModel')" v-model="queryParam.q"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="8">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('commodityManagement.category')">
                  <a-tree-select style="width:100%" :dropdownStyle="{maxHeight:'200px',overflow:'auto'}" allow-clear
                                 :treeData="categoryTree" v-model="queryParam.categoryId" :placeholder="$t('commodityManagement.pleaseCategory')">
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="8">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('reportQuery.warehouse')">
                  <a-select :placeholder="$t('popup.selectWarehouse')" v-model="queryParam.depotId" @change="onDepotChange"
                    :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children" allow-clear>
                    <a-select-option v-for="(item,index) in depotList" :key="index" :value="item.id">
                      {{ item.depotName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="6" :sm="24">
                  <a-button type="primary" @click="loadMaterialData(1)">{{$t('setailManagement.query')}}</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset(1)">{{$t('setailManagement.reset')}}</a-button>
                  <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? $t('setailManagement.putAway') : $t('setailManagement.open') }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                  </a>
                </a-col>
              </span>
              <template v-if="toggleSearchStatus">
                <!-- <a-col :md="6" :sm="24">
                  <a-form-item label="序列号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select placeholder="有无序列号" v-model="queryParam.enableSerialNumber">
                      <a-select-option value="1">有</a-select-option>
                      <a-select-option value="0">无</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col> -->

                
                <a-col :md="6" :sm="8">
                <a-form-item :label="$t('commodityManagement.batchNumber')" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <a-input ref="material" :placeholder="$t('popup.isNumber')" v-model="queryParam.color"></a-input>
                </a-form-item>
              </a-col>
                
                <!-- <a-col :md="6" :sm="8">
                  <a-form-item :label="$t('commodityManagement.batchNumber')" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                    <a-input ref="material" :placeholder="$t('popup.isNumber')" v-model="queryParam.organId"></a-input>
                  </a-form-item>
                </a-col> -->
              </template>
            </a-row>
          </a-form>
          <a-table
            ref="table"
            :scroll="scrollTrigger"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
            :loading="loading"
            :customRow="rowAction"
            @onSelect="onSelect"
            @change="handleTableChange">
            <template slot="customRenderEnableSerialNumber" slot-scope="enableSerialNumber">
              <a-tag v-if="enableSerialNumber==1" color="green">{{$t('commodityManagement.have')}}</a-tag>
              <a-tag v-if="enableSerialNumber==0" color="orange">{{$t('commodityManagement.nothing')}}</a-tag>
            </template>
            <template slot="customRenderEnableBatchNumber" slot-scope="enableBatchNumber">
              <a-tag v-if="enableBatchNumber==1" color="green">{{$t('commodityManagement.have')}}</a-tag>
              <a-tag v-if="enableBatchNumber==0" color="orange">{{$t('commodityManagement.nothing')}}</a-tag>
            </template>
          </a-table>
        </div>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import {filterObj, getMpListShort} from '@/utils/util'
  import {getMaterialBySelect, queryMaterialCategoryTreeList} from '@/api/api'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {getLanCode} from '@/lang';
  import Vue from 'vue'
  
  export default {
    name: 'JSelectMaterialModal',
    inject:{
      getConfig:{
        value:'getConfig',
        default:null
    }},
    mixins:[JeecgListMixin],
    components: {},
    props: ['rows', 'multi', 'barCode'],
    data() {
      return {
        modalWidth: 1450,
        dropTrigger: [],
        selectedKeys: [],
        selectedKeys1: [],
        checkedKeys: [],
        categoryTree: [],
        checkStrictly: true,
        iExpandedKeys: [],
        queryParam: {
          q: '',
          categoryId: '',
          depotId: '',
          enableSerialNumber: '',
          enableBatchNumber: ''
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        columns: [
          {dataIndex: 'mBarCode', title: this.$t('reportQuery.barcode'), align: 'left'},
          {dataIndex: 'name', title: this.$t('reportQuery.name')},
          {dataIndex: 'categoryName', title: this.$t('reportQuery.category')},
          {dataIndex: 'standard', title: this.$t('reportQuery.specification')},
          {dataIndex: 'model', title: this.$t('reportQuery.model')},
          {dataIndex: 'color', title: this.$t('reportQuery.color')},
          {dataIndex: 'unit', title: this.$t('reportQuery.unit')},
          // {dataIndex: 'sku', title: this.$t('commodityManagement.multiAttribute')},
          {dataIndex: 'stock', title: this.$t('reportQuery.inventory')},
          // {dataIndex: 'unitName', title: this.$t('reportQuery.unitName')},
          // {dataIndex: 'assistStock', title: this.$t('reportQuery.assistStock')},
          // {dataIndex: 'expand', title: this.$t('commodityManagement.extendedInformation')},
          // {dataIndex: 'enableSerialNumber', title: this.$t('inPrint.serialNumber'), align: "center",
          //   scopedSlots: { customRender: 'customRenderEnableSerialNumber' }
          // },
          // {dataIndex: 'enableBatchNumber', title: this.$t('commodityManagement.batchNumber'), align: "center",
          //   scopedSlots: { customRender: 'customRenderEnableBatchNumber' }
          // }
        ],
        scrollTrigger: {},
        dataSource: [],
        selectedRowKeys: [],
        selectMaterialRows: [],
        selectMaterialIds: [],
        title: this.$t('otherJS.selectCommodity'),
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + this.$t('setailManagement.common') + total + this.$t('setailManagement.strip')
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        departTree: [],
        depotList: [],
        visible: false,
        form: this.$form.createForm(this),
        loading: false,
        expandedKeys: [],
        disableMixinCreated: true,
        currentIndex:-1,
        dom:null,
      }
    },
    computed: {
      // 计算属性的 getter
      getType: function () {
        return this.multi == true ? 'checkbox' : 'radio';
      },
      actConfig() {
        
        if(typeof this.getConfig === 'function') return this.getConfig();
      },
    },
    watch: {
      barCode: {
        immediate: true,
        handler() {
          this.initBarCode()
        }
      }
    },
    created() {
      // 该方法触发屏幕自适应
      this.resetScreenSize()
      
    },
    methods: {
      // 右键点击下拉框改变事件
      dropStatus(visible) {
        if (visible == false) {
          this.dropTrigger = ''
        }
      },
      // 右键操作方法
      rightHandle(node) {
        this.dropTrigger = 'contextmenu'
        console.log(node.node.eventKey)
        this.rightClickSelectedKey = node.node.eventKey
        this.rightClickSelectedOrgCode = node.node.dataRef.orgCode
      },
      onCheck(checkedKeys, info) {
        console.log('onCheck', checkedKeys, info)
        this.hiding = false
        //this.checkedKeys = checkedKeys.checked
        // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
        if(this.checkStrictly){
          this.checkedKeys = checkedKeys.checked;
        }else{
          this.checkedKeys = checkedKeys
        }
        // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
      },
      onSelect(selectedKeys, e) {
        console.log('selected', selectedKeys, e)
        this.hiding = false
        let record = e.node.dataRef
        let params = {};
        params.id=record.id;
        // 是方法说明有传值
        if(typeof this.getConfig === 'function' && this.getConfig().organId){
          params.organId=this.getConfig().organId;
          console.log('666 :>> ', 666);
        }
        this.getTreeByParams(params)
        this.queryParam = {}
        
        if(typeof this.getConfig === 'function'){
          this.queryParam = Object.assign({},this.getConfig())
        }
        this.queryParam.categoryId = params.id
        this.onSearch()
      },
      //根据类别id加载类别树
      getTreeByParams(params) {
        queryMaterialCategoryTreeList(params).then((res) => {
          if (res) {
            this.treeData = [{
                children: [],
                checked: false,
                id: '',
                state: "open",
              title: getLanCode()==='en' ? 'All' : '全部',
              value: "1",
              key: "2"
            }]
            for (let i = 0; i < res.length; i++) {
              this.treeData.push(res[i])
            }
            console.log(this.treeData,999);
            
          }
        })
      },
      onExpand(expandedKeys) {
        // console.log('onExpand', expandedKeys)
        this.iExpandedKeys = expandedKeys
      },
      initBarCode() {
        if (this.barCode) {
          this.$emit('initComp', this.barCode)
        } else {
          // JSelectUserByDep组件bug issues/I16634
          this.$emit('initComp', '')
        }
      },
      loadMaterialData(arg) {
        // if(process.env.NODE_ENV === 'development'){
        //   let dataSource = Vue.ls.get('material_model_list') || []
        //   if(dataSource.length){
        //     this.dataSource = dataSource
        //     return;
        //   }
        // }
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        this.loading = true
        let params = this.getQueryParams()//查询条件
        console.log(params, '查询条件')
        getMaterialBySelect(params).then((res) => {
          if (res) {
            this.dataSource = res.rows
            Vue.ls.set('material_model_list',this.dataSource)
            this.ipagination.total = res.total
            if(res.total ===1) {
              this.title = this.$t('otherJS.selectCommodityAgain')
              this.$nextTick(() => this.$refs.material.focus());
            } else {
              this.title = this.$t('otherJS.selectCommodity')
            }
          }
        }).finally(() => {
          this.loading = false
        })
      },
      loadTreeData(){
        let that = this;
        let params = {};
        params.id='';
        params.organId = this.queryParam.organId
        queryMaterialCategoryTreeList(params).then((res)=>{
          if(res){
            that.categoryTree = [
            {
                children: [],
                checked: false,
                id: '',
                state: "open",
              title: this.$t('commodityManagement.all'),
              value: "1",
              key: "2"
            }
            ];
            for (let i = 0; i < res.length; i++) {
              let temp = res[i];
              that.categoryTree.push(temp);
              that.setThisExpandedKeys(temp)
            }
            
          }
        })
      },
      setThisExpandedKeys(node) {
        if (node.children && node.children.length > 0) {
          this.iExpandedKeys.push(node.key)
          for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
        }
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let realScreenWidth = window.screen.width
        this.modalWidth = realScreenWidth<1600?'1200px':'1450px'
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = {x: 800};
        } else {
          this.scrollTrigger = {};
        }
      },
      showModal(name) {
        this.visible = true;
        this.currentIndex = -1
        this.title = this.$t('otherJS.selectCommodity')
        if(name) this.queryParam.q = name
        if (typeof this.getConfig === 'function') {
          this.queryParam = Object.assign(this.queryParam,this.getConfig())
        }
        this.dropTrigger = 'contextmenu'
        this.$nextTick(() => {
          this.$refs.material.focus()
        this.loadTreeData()
        this.getDepotList()
        this.loadMaterialData();
        this.form.resetFields();
        });
        this.onPlusKey()
        // this.initDepotSelect()

      },
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.mpList = getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
        param.page = this.ipagination.current;
        param.rows = this.ipagination.pageSize;

        return filterObj(param);
      },
      getQueryField() {
        let str = 'id,';
        for (let a = 0; a < this.columns.length; a++) {
          str += ',' + this.columns[a].dataIndex;
        }
        return str;
      },
      searchReset(num) {
        let that = this;
        if (num !== 0) {
          that.queryParam = {};
          that.loadMaterialData(1);
        }
        that.selectedRowKeys = [];
        that.selectMaterialIds = [];
      },
      close() {
        this.searchReset(0);
        this.dom = null
        this.visible = false;
      },
      handleTableChange(pagination, filters, sorter) {
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc';
        }
        this.ipagination = pagination;
        this.loadMaterialData();
      },
      handleSubmit() {
        let that = this;
        this.getSelectMaterialRows();
        console.log(that.selectMaterialRows)
        console.log(that.selectMaterialIds)
        that.$emit('ok', that.selectMaterialRows, that.selectMaterialIds);
        that.searchReset(0)
        that.close();
      },
      //获取选择信息
      getSelectMaterialRows(rowId) {
        let dataSource = this.dataSource;
        // console.log(this.dataSource)
        let materialIds = "";
        this.selectMaterialRows = [];
        let arrId = []
        for (let i = 0, len = dataSource.length; i < len; i++) {
          if (this.selectedRowKeys.includes(dataSource[i].id)) {
            // dataSource[i].materialId = dataSource[i].id
            arrId.push(dataSource[i].id)
            this.selectMaterialRows.push(dataSource[i]);
            materialIds = materialIds + "," + dataSource[i].mBarCode
          }
        }
        arrId = arrId.toString()
        localStorage.setItem('materialIds', arrId)
        this.selectMaterialIds = materialIds.substring(1);
      },
      getDepotList() {
        let that = this;
        getAction('/depot/findDepotByCurrentUser').then((res) => {
          if(res.code === 200){
            that.depotList = res.data
          }
        })
      },
      initDepotSelect() {
        if(this.rows) {
          if(JSON.parse(this.rows).depotId){
            this.queryParam.depotId = JSON.parse(this.rows).depotId-0
          }
        }
      },
      onDepotChange(value) {
        this.queryParam.depotId = value
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
      },
      onSearch() {
        if(this.dataSource && this.dataSource.length===1) {
          if(this.queryParam.q === this.dataSource[0].mBarCode||
            this.queryParam.q === this.dataSource[0].name||
            this.queryParam.q === this.dataSource[0].standard||
            this.queryParam.q === this.dataSource[0].model||
            this.queryParam.q === this.dataSource[0].color) {
            let arr = []
            arr.push(this.dataSource[0].id)
            this.selectedRowKeys = arr
            this.handleSubmit()
          } else {
            this.loadMaterialData(1)
          }
        } else {
          if(this.selectedRowKeys.length === 1){
            this.handleSubmit()
            return
          }
          this.loadMaterialData(1)
        }
      },
      
      /**
       * 监听按键
       */
      onPlusKey() { // 监听键盘
        this.$nextTick(()=>{
          this.dom = document.querySelector('#select-material-modal')
        this.dom.onkeydown = (e)=> {         
          let key = window.event.keyCode; 
          console.log('key :>> ', key);
          // up
          if(key === 38 && this.visible){
            if(this.dataSource && this.dataSource.length){
              if(this.currentIndex > 0){
                this.currentIndex --
              }else{
                this.currentIndex = 0
              }
              this.selectedRowKeys = [this.dataSource[this.currentIndex].id]
            }
          }
          // down
          if(key === 40 && this.visible){
            if(this.dataSource && this.dataSource.length){
              if(this.currentIndex < this.dataSource.length -1){
                this.currentIndex ++
              }
              this.selectedRowKeys = [this.dataSource[this.currentIndex].id]
            }
          }
          const pageTotal = Math.ceil(this.ipagination.total / this.ipagination.pageSize)
          // left
          if(key === 37 && this.visible){
            if(this.ipagination.current > 1){
              this.ipagination.current --
              this.loadMaterialData()
            }
          }
          // right
          if(key === 39 && this.visible){
            if(this.ipagination.current < pageTotal){
              this.ipagination.current ++
              this.loadMaterialData()
            }
          }
        }
        })
      },
      modalFormOk() {
        this.loadMaterialData()
      },
      rowAction(record, index) {
        return {
          on: {
            click: () => {
              if(this.selectedRowKeys.includes(record.id)){
                let index = this.selectedRowKeys.findIndex(val=>val === record.id)
                if(index>-1){
                  this.selectedRowKeys.splice(index,1)
                }
              }else{
                this.selectedRowKeys.push(record.id)
              }
              
            },
            dblclick: () => {
              let arr = []
              arr.push(record.id)
              this.selectedRowKeys = arr
              this.handleSubmit()
            }
          }
        }
      }
    }
  }
</script>

<style>
  .mater-a40596bz .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  .mater-a40596bz #components-layout-demo-custom-trigger .trigger {
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color .3s;
  }
 .mater-a40596bz .ant-tree >li:first-child .ant-tree-node-content-wrapper{
    padding-top: 7px;
    margin-bottom: 7px;
    font-weight: bold;
    /* color: #409eff; */
    font-size: 16px;
    /* position: absolute; */
}
.mater-a40596bz .ant-tree {
    display: inline-block;
    height: 24px;
    margin: 0;
    padding: 0 5px;
    color: rgba(0, 0, 0, 0.65);
    font-weight: bold;
    line-height: 24px;
    text-decoration: none;
    vertical-align: top;
    border-radius: 2px;
    cursor: pointer;
    transition: all 0.3s;
    border: 1psx solid red;
}
</style>